package com.example.Cairodio;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

/**
 * This class is concerned with performing the needed visual editing operations
 * for the image in order to cast in in a post card form.
 * 
 * @author AnwaRowers
 * 
 */
public class MyPhotoShop {
	private Canvas myCanvas;
	TouristicPostCard card;

	public MyPhotoShop(TouristicPostCard card) {
		this.card = card;
	}

	/**
	 * converts a given bitmap to its array of bytes.
	 * 
	 * @param bitmap
	 *            input Bitmap.
	 * @return the array of bytes associated with the given bitmap.
	 */
	public static byte[] bitmap2Bytes(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		byte[] bMapArray = baos.toByteArray();
		return bMapArray;
	}

	/**
	 * Responsible for adding the frame to the captured image, along with adding
	 * the location and the date stamp.
	 * 
	 * @param input
	 *            the bitmap of the captured image
	 * @return the bitmap of the post card.
	 */
	protected Bitmap makeCard(Bitmap input) {
		try {
			int scale = 1;
			Bitmap capturedTemp = input.copy(Config.ARGB_8888, true);
			Bitmap captured = Bitmap.createScaledBitmap(capturedTemp,
					185 * scale, 240 * scale, true);
			Bitmap frame = BitmapFactory.decodeResource(card.getResources(),
					R.drawable.berwaz);
			Bitmap origin = Bitmap.createBitmap(frame.getWidth(),
					frame.getHeight(), Config.ARGB_8888);
			myCanvas = new Canvas(origin);
			myCanvas.drawBitmap(frame, 0, 0, null);
			myCanvas.drawBitmap(captured, 60 * scale, 60 * scale, null);
			this.addText(card.getPlace());
			return origin;
		} catch (Exception e) {
			String errorMsg = e.getMessage();
			Toast.makeText(this.card, errorMsg, 1).show();
			return input;
		} catch (Error error) {
			String errorMsg = error.getMessage();
			Toast.makeText(this.card, errorMsg, 1).show();
			return input;
		}
	}

	/**
	 * Adds the necessary text to the post card.
	 * 
	 * @param text
	 *            the string to be added to the post card.
	 */
	protected void addText(String text) {
		if (myCanvas != null) {
			Paint myPaint = new Paint();
			myPaint.setTextSize(20f);
			myPaint.setColor(Color.BLACK);
			if (text.length() > 16) {

			}
			myCanvas.drawText(text, 30, 330, myPaint);
			myCanvas.drawText(currentDate("dd/MM/yyyy HH:mm"), 50, 370, myPaint);
		}
	}

	/**
	 * returns current date.
	 * 
	 * @return the current date in a string format
	 */
	protected static String currentDate(String s) {
		DateFormat dateFormat = new SimpleDateFormat(s);
		Date date = new Date();
		return (dateFormat.format(date));
	}

	/**
	 * Saves the file into the photo gallery
	 * 
	 * @param bmp
	 *            the image to be written
	 * @param fileName
	 *            the name under which the file would be saved.
	 */
	protected void writeFile(Bitmap bmp, String fileName) {

		try {

			File sdCard = Environment.getExternalStorageDirectory();
			File dir = new File(sdCard.toString() + "/dcim/Camera/");
			dir.mkdirs();
			File file = new File(dir, fileName);
			FileOutputStream f = new FileOutputStream(file);
			bmp.compress(CompressFormat.JPEG, 100, f);
			f.flush();
			f.close();
			MediaStore.Images.Media.insertImage(card.getContentResolver(),
					file.getAbsolutePath(), fileName, fileName);

			Toast.makeText(card, "Successfully written!", 1).show();
		} catch (Exception e) {
			String msg = e.getMessage();
			Toast.makeText(card, msg, 1).show();
		} catch (Error e) {
			String msg = e.getMessage();
			Toast.makeText(card, msg, 1).show();

		}
	}

	/**
	 * A method that manipulates a string, adding some random number to the end
	 * of its name. It would be useful for a fixed function to avoid overwriting
	 * files.
	 * 
	 * @param s
	 * @return
	 */
	public static String myHash(String s) {
		s = s.replace(' ', '_');
		String parts[] = s.split("\\.", 0);
		System.out.println(parts.length);
		System.out.println("Parts: " + parts[0] + " " + parts[1]);
		parts[0] += (int) (Math.random() * 10000) % 10000;
		String result = parts[0] + "." + parts[1];
		return result;
	}

	/**
	 * Saves the file into the application's photo gallery
	 * 
	 * @param bmp
	 *            the image to be written
	 * @param fileName
	 *            the name under which the file would be saved.
	 */
	public boolean writeImage(Bitmap bitmap, String s) throws Exception {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		String sep = File.separator;
		String fileName = Environment.getExternalStorageDirectory() + sep
				+ "DCIM" + sep + "Camera" + sep + "Cairodio_" + s;
		File f = new File(myHash(fileName));
		boolean result = f.createNewFile();
		// write the bytes in file
		FileOutputStream fo = new FileOutputStream(f);
		fo.write(baos.toByteArray());
		fo.flush();
		fo.close();
		Toast.makeText(card, card.getString(R.string.successfully_written), 1)
				.show();
		return result;
	}
}
